package hot100;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Deque;

public class OrangesRotting {
    private int minute = 0;

    private Deque<int[]> que = new ArrayDeque<>();

    private int[][] dir = {{1,0},{0,1},{-1,0},{0,-1}};

    public int orangesRotting(int[][] grid) {
        //bfs，图的层序遍历
        //先将烂橘子的坐标入队
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 2) {
                    que.addLast(new int[]{i,j});
                }
            }
        }

        bfs(grid,m,n);

        //最后判断是否还有不会腐烂的
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    return -1;
                }
            }
        }

        return minute > 0 ? minute - 1 : 0;
    }

    private void bfs(int[][] grid,int m, int n) {
        //记录当前层的数量
        int curLevCount = que.size();
        while (!que.isEmpty()) {
            int[] cur = que.removeFirst();
            int curY = cur[0];
            int curX = cur[1];
            curLevCount--;
            for (int i = 0; i < 4; i++) {
                int nextY = curY + dir[i][0];
                int nextX = curX + dir[i][1];

                if (nextY < 0 || nextY >= m || nextX < 0 || nextX >= n) continue;

                if (grid[nextY][nextX] == 1) {
                    grid[nextY][nextX] = 2;
                    que.addLast(new int[]{nextY,nextX});
                }
            }
            if (curLevCount == 0) {
                //一层遍历完毕
                curLevCount = que.size();
                minute++;
            }
        }
    }

    @Test
    public void test() {
        int[][] grid = {{2,1,1},{1,1,0},{0,1,1}};
        orangesRotting(grid);
    }
}
